package com.book.adapter;

import com.alibaba.fastjson.JSONObject;
import com.book.pojo.UserInfo;
import com.book.service.UserInfoService;
import com.book.utils.HttpClientUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 三方登录对象适配器
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class Login3rdAdapter  implements Login3rdTarget{

    @Value("${gitee.state}")
    private String giteeState;

    @Value("${gitee.token.url}")
    private String giteeTokenUrl;

    @Value("${gitee.user.url}")
    private String giteeUserUrl;

    @Value("${gitee.user.prefix}")
    private String giteeUserPrefix;

    // 这里使用注入，使其成为 Login3rdAdapter对象适配器，原文中的 UserInfoService 是一个class，使用继承来实现的
    public final UserInfoService userInfoService;

    @Override
    public String loginByGitee(String code, String state) {

//        if (!giteeState.equals(state)) {
//            throw new UnsupportedOperationException("InValid state");
//        }
        // 请求gitee平台获取token，并携带code
        String tokenUrl = giteeUserUrl.concat(code);
        // 获取token
        JSONObject tokenResponse = HttpClientUtils.execute(tokenUrl, HttpMethod.POST);
        String accessToken = String.valueOf(tokenResponse.get("access_token"));
        log.info("用户Token {}",accessToken);
        // 获取用户信息
        String userUrl = giteeTokenUrl.concat(accessToken);
        JSONObject userInfoResponse = HttpClientUtils.execute(userUrl, HttpMethod.GET);
        log.info("用户信息 {}",userInfoResponse);
        String username = giteeUserPrefix.concat(userInfoResponse.getString("name"));
        String password = username;
        // 自动注册和登录
        return autoRegister3rdAndLogin(username,password);
    }

    private String autoRegister3rdAndLogin(String username, String password) {
        if (userInfoService.checkUserExists(username)) {
            return userInfoService.login(username, password);
        }
        UserInfo userInfo = new UserInfo().setUsername(username)
                .setUserPassword(password)
                .setUserEmail(username)
                .setCreateDate(new Date())
                ;
        userInfoService.save(userInfo);
        return userInfoService.login(username, password);
    }

    @Override
    public String loginByWechat(String code, String state) {
        return null;
    }

    @Override
    public String loginByQQ(String code, String state) {
        return null;
    }
}
